package geowiki.data;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Simply utility class to create URLs and queries for the YQL API.
 */
public class YQLQuery {

	private static final String YQL_API_URL = "http://query.yahooapis.com/v1/public/yql";
	private static final String YQL_RESPONSE_FORMAT = "xml";

	/**
	 * Returns a URL to query for all places from given web page.
	 * 
	 * @param documentURL
	 *            The URL of the web page.
	 * @return A URL to query YQL API with.
	 */
	public static String getAllPlacesFromWebpage(String documentURL) {
		return getAllPlaces("documentURL=\"" + documentURL + "\"");
	}

	/**
	 * Returns a URL to query for all places from given HTML snippet.
	 * 
	 * @param htmlContent
	 *            The content to parse (HTML elements are ok).
	 * @return A URL to query YQL API with.
	 */
	public static String getAllPlacesFromHTMLContent(String htmlContent) {
		return getAllPlaces("documentContent=\"" + htmlContent + "\"");
	}

	protected static String getAllPlaces(String whereClause) {
		String query = "SELECT * FROM geo.placemaker WHERE " + whereClause + " AND documentType=\"text/html\"";
		return getYQLRestURL(query);
	}

	public static String getAllLinksFromWebpage(String wikipediaURL) {
		String query = "SELECT * FROM html WHERE url=\"" + wikipediaURL
				+ "\" AND xpath='//div[@id=\"bodyContent\"]//a'";
		return getYQLRestURL(query);
	}

	public static String getMainContentDivFromWikiArticle(String wikipediaURL) {
		String query = "SELECT * FROM html WHERE url=\"" + wikipediaURL + "\" AND xpath='//div[@id=\"bodyContent\"]'";
		return getYQLRestURL(query);
	}
	
	public static String getParagraphsFromWikiArticle(String wikipediaURL) {
		String query = "SELECT * FROM html WHERE url=\"" + wikipediaURL + "\" AND xpath='//div[@id=\"bodyContent\"]/p'";
		return getYQLRestURL(query);
	}

	protected static String getYQLRestURL(String yqlQuery) {
		try {
			String encodedQuery = URLEncoder.encode(yqlQuery, "UTF-8");
			return YQL_API_URL + "?q=" + encodedQuery + "&format=" + YQL_RESPONSE_FORMAT;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

}
